﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ChapterX.Data.DigitizationDSTableAdapters;
using System.Data;
using ChapterX.BusinessFacade;
using ChapterX.Common;

namespace ChapterX.Auth.Teacher
{
    public partial class ApplicationEntry : ChapterX.Model.PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindApplicationList();
            }
        }

        protected void BindApplicationList()
        {
            try
            {
                DigitizationViewTableAdapter adapter =
                    new DigitizationViewTableAdapter();
                DataTable appList = null;

                if (CurrentUserInfo.IsLibrarian)
                {
                    //TODO
                    appList = adapter.GetData();
                                    }
                else if (CurrentUserInfo.IsTeacher)
                {
                    //get digitization by teacher and status 
                    //状态为申请被拒绝的，如何处理？ 不处理，为已拒绝的申请提供重新申请的功能

                    appList = adapter.GetDigitizationByTeacherAndStatusFromView(CurrentUserInfo.Username, 
                        (int)CommonDefinition.DigitizationStatus.defaultStatus);
                }
                else
                {
                    throw new UnexpectedException();
                }

                this.BookSelector.DataSource = appList;
                this.BookSelector.DataValueField = "BookId";
                this.BookSelector.DataTextField = "Title";
                this.BookSelector.DataBind();
            }
            catch (Exception ex)
            {
                SetErrorMessage("数据绑定失败。");
                Logger.Log(ex);
            }
        }

        protected void Submit_Click(object sender, EventArgs e)
        {
            try
            {
                String bookId = this.BookSelector.SelectedValue;

                bool result = false;
                DigitizationSystem ds = new DigitizationSystem();
                result = ds.UpdateDigitizationStatus(Int32.Parse(bookId),
                   (int)CommonDefinition.DigitizationStatus.submitted);

                if (result)
                {
                    SetInfoMessage("数字化申请提交成功");
                    BindApplicationList();
                }
                else
                    SetErrorMessage("数字化申请提交失败");
            }
            catch(Exception ex)
            {
                SetErrorMessage("数字化申请提交失败");
                Logger.Log(ex);
            }
        }
    }
}
